<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member extends MY_Controller {
	private $checkkey='mcheckcode';
	function __construct(){
		parent::__construct();
		$this->needLogin();


	}
	
	function cherkprofile(){
			$row=$this->member_info();
			if($row['isdetail']=='1'){
				redirect('member/profile');
			}	
	}

	function index(){

		//作品列表
		$where=array('mid'=>$this->member->mid);
		$worklist=$this->Data_model->getData($where,'iscomm DESC,id DESC',0,0,'works');
		foreach ($worklist as $key => $value) {
			$worklist[$key]['puttime']=date('Y.m.d',$value['puttime']);
			$worklist[$key]['href']=site_url('member/work/'.$value['id']);
		}
		$worklist=$this->getExtends($worklist);
		//print_r($worklist);
		$memberinfo=$this->member_info();
		$this->mview('main',array(
			'currentnav'=>'会员中心',
			'worklist'=>$worklist,
			'memberinfo'=>$memberinfo,
			//'msglist'=>$msglist,
				'latest'=>$this->getLatest()
			));
	}

	/**
	 * 保存资料
	 */
	function saveinfo(){
		$post=$this->input->post(NULL,TRUE);

		$result=array();
		if(empty($post)){
			
		}else{
			$data = array_intersect_key($post,array('content'=>'','title'=>'','isdefault'=>''));
			if(isset($data['title']))
				$data['title']=htmlspecialchars($data['title']);
			if(isset($data['content']))
				$data['content']=htmlspecialchars($data['content']);
			if($data['isdefault']){
				$data['isdefault']=1;

				//取消其它默认选项
				$this->Data_model->editData(array('mid'=>$this->member->mid),array('isdefault'=>0),'member_data');
			}else{
				unset($data['isdefault']);
			}
			$row=$this->Data_model->getSingle(array('mid'=>$this->member->mid),'member_data','isdefault DESC');
			$data['uptime']=time();
			if(empty($row)){
				$data['mid']=$this->member->mid;
				$data['isdefault']=1;
				$this->Data_model->addData($data,'member_data');
			}else{
				$this->Data_model->editData(array('id'=>$row['id']),$data,'member_data');
			}

		}
		echo json_encode($result);
	}

	/**
	 * 个人信息
	 */
	function profile(){
		$post=$this->input->post(NULL,TRUE);
		if(!empty($post)){
			$result=array();
			//
			$pwd=$post['mpwd'];
			if(!empty($pwd) ){
				if($pwd != $post['rmpwd']){
					$result['errorcode']=1;
					$result['error']='两次密码输入不一致';
					echo json_encode($result);
					exit;
				}
				
				if(empty($_POST['oldpwd'])){
					$result['errorcode']=1;
					$result['error']='请输入旧密码确认身份';
					echo json_encode($result);
					exit;
				}
				
			}
			
			$data=array_intersect_key($post,array('mnick'=>''));
			if($this->member->save($data)){
				$result['errorcode']=0;
				$result['error']='资料保存成功';
				$result['url']='member/index';
			}else{
				$result['errorcode']=1;
				$result['error']=$this->member->getMessage();
			}
			echo json_encode($result);
		}else{
			$memberinfo=$this->member_info();
			$this->mview('profile',array('memberinfo'=>$memberinfo,));
		}
	}

	function leader(){
		$this->mview('leader');
	}

	/**
	 * 保存资料
	 */
	function savework(){
		$post=$this->input->post(NULL,TRUE);

		$result=array();
		if(empty($post)){
			$result['errorcode']=1;
			$result['error']='';
		}else{
			$data = array_intersect_key($post,array('id'=>'','content'=>'','title'=>'','isdefault'=>''));
			if(empty($post['id'])){
				$result['errorcode']=1;
				$result['error']='数据错误！';
			}else{

				if(isset($data['title']))
					$data['title']=htmlspecialchars($data['title']);
				if(isset($data['content']))
					$data['content']=htmlspecialchars($data['content']);
				$data['edittime']=time();

				$this->Data_model->editData(array('id'=>$post['id']),$data,'works');
				$result['errorcode']=0;
				//$result['error']='更改成功';
			}

		}
		echo json_encode($result);
	}
	/**
	 * 保存资料
	 */
	function savemember(){
		$post=$this->input->post(NULL,TRUE);

		$result=array();
		if(empty($post)){
			$result['errorcode']=1;
			$result['error']='';
		}else{
			$data = array_intersect_key($post,array('city'=>'','sex'=>'','age'=>'','contact'=>'','profession'=>'','honor'=>'','story'=>'','honor'=>''));
			if(empty($post['id'])){
				$result['errorcode']=1;
				$result['error']='数据错误！';
			}else{

				if(isset($data['story']))
					$data['story']=htmlspecialchars($data['story']);
				$this->Data_model->editData(array('mid'=>$post['id']),$data,'member');
				$result['errorcode']=0;
				$result['error']='更新成功！';
				//}
			}

		}
		echo json_encode($result);
	}


	function works(){
		$lastid=$this->uri->segment(3);
		
		$where=array('mid'=>$this->member->mid);
		if(!empty($lastid)){
			$where['id <']=$lastid;
		}

		$worklist=$this->Data_model->getData($where,'id DESC',0,5,'works');

		$worklist=$this->getExtends($worklist);

		$this->mview('works',array(
			'currentnav'=>'作品列表',
			'wlist'=>$worklist,
				'latest'=>$this->getLatest()
			));
	}

	function work(){
		$wid=$this->uri->segment(3);
		$work = $this->Data_model->getSingle(array('id'=>(int)$wid,'mid'=>$this->member->mid),'works');
		if(empty($work)){
			$this->showMessage('作品未找到','您查看的作品不存在或已删除！');
		}
		$work['images']=$this->Data_model->getData(array('wid'=>$work['id']),'id ASC',0,10,'work_image');

		$where=array('wid'=>$wid,'reid'=>0);
		$this->Data_model->db->from('work_comm wc')->select('wc.*,m.mname,m.mnick,m.avatar')->join('member m','m.mid=wc.mid','left');
		$msglist=$this->Data_model->getData($where,'wc.id DESC',0,5);
		
		//回复
		foreach($msglist as $key=> $val){
			$where=array('wid'=>$val['wid'],'reid'=>$val['id']);
			$this->Data_model->db->from('work_comm wc')->select('wc.*,m.mname,m.mnick,m.avatar')->join('member m','m.mid=wc.mid','left');
			$remsglist=$this->Data_model->getData($where,'wc.id DESC',0,1);	
			$msglist[$key]['remsglist']=array();
			if(count($remsglist)>0){
				$msglist[$key]['remsglist']=$remsglist[0];
			}
			
		}	
		//print_r($msglist);
		//echo $this->Data_model->db->last_query();
		$memberinfo=$this->member_info();
		$this->mview('work',array(
			'currentnav'=>'作品详情',
			'work'=>$work,
			'memberinfo'=>$memberinfo,
			'msglist'=>$msglist,
			'latest'=>$this->getLatest()
			));
	}

	function invite(){
		$post=$this->input->post(NULL);
		if(!empty($post)){
			//$emailcfg=$this->Cache_model->loadConfig('mail');

			$this->load->library('email');
			if(!$this->email->valid_email($post['email'])){
				echo json_encode(array('errorcode'=>0,'message'=>'邮件地址格式不正确！'));
			}else{
				$member=$this->Data_model->getSingle(array('email'=>$post['email']),'member');
				if(!empty($member)){
					if($member['mid']==$this->member->mid){
						$messages="（⊙o⊙） 您怎么能邀请自己呢？";
					}else{
						$messages="您的好友已经是sokerr的一员啦！";
					}
					echo json_encode(array('errorcode'=>1,'message'=>$messages));
						exit;
				}
				//生成验证码并发送邮件
				$vcode=$this->member->mid.base_convert(microtime(), 10, 36).base_convert(str_shuffle(microtime()), 10, 36);

				//过滤内容
				$post['content']=htmlspecialchars($post['content']);
				$post['content']=str_replace(array('\r\n','\r','\n'), '<br />', $post['content']);

				//是否存在
				$irow=$this->Data_model->getSingle(array('email'=>$post['email']),'invite');
				if(empty($irow)){
					$this->Data_model->addData(array(
						'mid'=>$this->member->mid,
						'email'=>$post['email'],
						'code'=>$vcode,
						'time'=>time(),
						'content'=>$post['content']
						),'invite');
				}else{
					//未过期
					if($irow['time']>time()-3*24*60*60){
						echo json_encode(array('errorcode'=>1,'message'=>'已经邀请过啦！'));
						exit;
					}else{
						$this->Data_model->editData(
							array('email'=>$post['email']),
							array(
							'mid'=>$this->member->mid,
							'email'=>$post['email'],
							'code'=>$vcode,
							'time'=>time(),
							'content'=>$post['content']
							),'invite');
					}
				}

				$html=file_get_contents(FCPATH.'data/template/sokerr/invite.tpl');

				$url = site_url('auth/register/'.$vcode);
				$fromname=$this->member->mnick;
				if(empty($fromname)){
					$fromname=$this->member->mname;
				}
				$post['content']='你的好友'.$fromname.'邀请你来sokrr！'.$post['content'];
				
				
				$html=str_replace(array('{linkurl}','{invitecont}','{imgurl}'), array($url,$post['content'],site_url('public/images/invite.jpg')), $html);
				
			
				$this->sendMail(array(
					'email'=>$post['email'],
					'title'=>'来自sokerr的邀请！',
					'content'=>$html
					));
				echo json_encode(array('errorcode'=>0,'message'=>'信息已发送！'));
			}
		}else{
			$this->view('invite',array('currentnav'=>'邀请好友'));
		}
	}

	function avatar(){
		$post=$this->input->post(NULL);
		$avatar=$this->member->avatar;
		if(empty($avatar))$avatar='/public/images/400.jpg';
		$avatar_source='/public/images/400.jpg';
		if(!empty($post)){
			$attrconfig = $this->Cache_model->loadConfig('attr');
			$save_path = '/data/attachment/'.$attrconfig['userfolder'].'/'.$this->member->mname.'/';
			if (!file_exists(FCPATH.$save_path)) {
				mkdir(FCPATH.$save_path,0777,TRUE);
			}
			//裁剪头像
			$config['image_library'] = 'gd2';
			$config['source_image'] = FCPATH.$avatar;
			//$config['create_thumb'] = FALSE;
			$config['maintain_ratio'] = FALSE; //强制比例
			$config['width'] = (int)$post['width'];
			$config['height'] = (int)$post['height'];
			$config['x_axis'] = (int)$post['x1'];
			$config['y_axis'] = (int)$post['y1'];
			$config['new_image']=FCPATH.$save_path.'avatar.'.substr($avatar, stripos($avatar, '.')+1);
			$this->load->library('image_lib',$config);
			$this->image_lib->crop();
			$filename=str_replace('-source', '', $avatar);
			$this->Data_model->editData(array('mid'=>$this->member->mid,),array('avatar'=>$filename),'member');
			$result=array('errorcode'=>0,'message'=>'裁剪成功！');
			echo json_encode($result);
		}else{
			$memberinfo=$this->member_info();
			$this->mview('avatar',array(
				'css'=>'imagearea',
				'avatar'=>$avatar,
				'avatar_source'=>$avatar_source,
				'memberinfo'=>$memberinfo,
				'currentnav'=>'上传头像'
				));
		}
	}

	//头像上传
	public function avatarupload(){
		$attrconfig = $this->Cache_model->loadConfig('attr');
		$save_path = '/data/attachment/'.$attrconfig['userfolder'].'/'.$this->member->mname.'/';
		if (!file_exists(FCPATH.$save_path)) {
			mkdir(FCPATH.$save_path,0777,TRUE);
		}
		$uploadconfig['upload_path'] = FCPATH.$save_path;
		$uploadconfig['allowed_types'] = 'jpg|png|gif';
		$uploadconfig['max_size'] = $attrconfig['attr_maxsize']?$attrconfig['attr_maxsize']:0;
		$uploadconfig['encrypt_name']  = TRUE;
		$uploadconfig['remove_spaces']  = TRUE;
		$uploadconfig['overwrite']=TRUE;
		$uploadconfig['file_name']='avatar-source';
		$this->load->library('upload', $uploadconfig);
		if(!$this->upload->do_upload('avatar')){
			$result = array('errorcode'=>1,'message'=>$this->upload->display_errors('',''));
			//$this->showMessage('上传失败',$this->upload->display_errors('',''),site_url('member/avatar'));
		}else{
			$data = $this->upload->data();
			//将图像裁剪至400X400
			$config['image_library'] = 'gd2';
			$config['source_image'] = FCPATH.$save_path.$data['file_name'];
			//$config['create_thumb'] = FALSE;
			$config['maintain_ratio'] = TRUE;
			$config['width'] = 400;
			$config['height'] = 400;
			$this->load->library('image_lib',$config);
			$this->image_lib->resize();

			$this->Data_model->editData(array('mid'=>$this->member->mid,),array('avatar'=>$save_path.$data['file_name']),'member');
			$result = array('errorcode'=>0,'message'=>'上传成功','image'=>base_url($save_path.$data['file_name']));
			//$this->showMessage('上传成功','头像已经成功上传！',site_url('member/avatar'));
		}
		echo json_encode($result);

	}

	function message(){
		$action=$this->uri->segment(3);
		$actions=array('inbox'=>'我收到的私信','outbox'=>'我发出的私信','dialogue'=>'私信对话记录'/*,'jobs'=>'工作申请记录'*/);
		if(empty($action) || !array_key_exists($action,$actions)){
			$action='inbox';
		}

		//读取消息列表
		switch($action){
			case 'inbox':
			$where=array('mc.cid'=>$this->member->mid,'mc.issys'=>0,'mc.reid'=>0);
			break;
			case 'outbox':
			$where=array('mc.mid'=>$this->member->mid,'mc.issys'=>0,'mc.reid'=>0);
			break;
			case 'dialogue':
			$tid=(int)$this->uri->segment(4);
			$where='((mc.cid='.$this->member->mid .' AND mc.mid='.$tid.') OR (mc.mid='.$this->member->mid .' AND mc.cid='.$tid.' )) AND mc.issys=0';
			break;
			case 'jobs':
			$where=array('mc.cid'=>$this->member->mid,'mc.issys'=>1);
			break;
		}
		
		$this->Data_model->db->from('mem_comm mc')
			->select('mc.*,m.mname,m.mnick,m.avatar,md.title as mtitle');
		if($action == 'outbox'){
			$this->Data_model->db->join('member m','m.mid=mc.cid','left');
		}else{
			$this->Data_model->db->join('member m','m.mid=mc.mid','left');
		}
		$this->Data_model->db->join('member_data md','m.mid=md.mid','left');
		$msglist=$this->Data_model->getData($where,'mc.id DESC',0,5);

		foreach ($msglist as $key => $msg) {
			$msglist[$key]['mnick']=empty($msg['mnick'])?$msg['mname']:$msg['mnick'];
			$msglist[$key]['puttime']=date('Y-m-d H:i:s',$msg['puttime']);
			if($msg['mid']==$this->member->mid){
				$msglist[$key]['spaceurl']=site_url('member');
			}else{
				$msglist[$key]['spaceurl']=site_url('space/'.$msg['mid']);
			}
		}

		$this->view('member_message',array(
			'currentnav'=>$actions[$action],
			'actions'=>$actions,
			'action'=>$action,
			'msglist'=>$msglist
			));
	}

	//发送消息
	function sendmessage(){

	}

	//发布作品
	function publish(){
		$wid=(int)$this->uri->segment(3);
		$post=$this->input->post(NULL,TRUE);
		if(!empty($post)){
			$result=array();
			$ispass=true;
			$post = array_intersect_key($post,array('title'=>'','image'=>'','iscomm'=>'','summary'=>'','content'=>''));
			//发布作品
			if(empty($post['title'])){
				$result['errorcode']=1;
				$result['error']='请填写主题';
				$ispass=false;
			}
			if($ispass){
				if(empty($post['image'])){
					$result['errorcode']=1;
					$result['error']='请上传图片';
					$ispass=false;
				}
			}
			if($ispass){
				if(empty($post['content'])){
					$result['errorcode']=1;
					$result['error']='请填写内容';
					$ispass=false;
				}
			}

			if($ispass){
				//内容过滤
				$post['title']=htmlspecialchars($post['title']);

				$images=(array)$post['image'];
				if(empty($post['imagedefault'])){
					$post['image']=$images[0];
				}else{
					$post['image']=$post['imagedefault'];
				}
				$post['iscomm'] = empty($post['iscomm'])?0:1;
				if(empty($post['summary'])){
					$post['summary']=$post['content'];
				}
				$post['summary']=strip_tags($post['summary']);

				//$post['content']=$post['content'];

				
				if(empty($wid)){
					//固定值
					$post['mid']=$this->member->mid;
					$post['puttime']=time();
					$post['edittime']=$post['puttime'];

					$this->Data_model->addData($post,'works');
					$wid=$this->Data_model->db->insert_id();
					$result['errorcode']=0;
					$result['message']='发表成功！';
				}else{
					//固定值
					$post['edittime']=time();

					$this->Data_model->editData(array(
						'mid'=>$this->member->mid,
						'id'=>$wid
						),$post,'works');
					$result['errorcode']=0;
					$result['message']='修改成功！';
				}
				if(!empty($wid)){
					$this->Data_model->db
						->where(array('mid'=>$this->member->mid))
						->where_in('image',$images)
						->update('work_image',array('wid'=>$wid));
					/*$this->Data_model->db->where(array('wid'=>$wid))->delete('work_image');
					foreach ($images as $key => $value) {
						if(!empty($value)){
							$this->Data_model->addData(array(
								'wid'=>$wid,
								'image'=>$value
								),'work_image');
						}
					}*/
				}
				$result['url']=site_url('member');
				show_jsonmsg($result);
			}else{
				show_jsonmsg($result);
			}
		}else{
			$work=$this->Data_model->getSingle(array(
						'mid'=>$this->member->mid,
						'id'=>$wid
						),'works');
			if(empty($work)){
				$work=array(
					'title'=>'',
					'image'=>'',
					'iscomm'=>'',
					'summary'=>'',
					'content'=>'');
			}
			$memberinfo=$this->member_info();
			$this->mview('publish',array(
				'currentnav'=>'发布作品',
				'memberinfo'=>$memberinfo,
				'work'=>$work
				));
		}
	}

	function deletework(){
		$wid=$this->uri->segment(3);
		$work=$this->Data_model->getSingle(array('id'=>$wid,'mid'=>$this->member->mid),'works');
		if(empty($work)){
			echo json_encode(array('errorcode'=>1,'message'=>'要删除的作品不存在！'));
		}else{
			@unlink(FCPATH.$work['image']);
			$this->Data_model->db->where(array('wid'=>$wid))->delete('work_comm');
			$this->Data_model->db->where(array('wid'=>$wid))->delete('work_good');
			$this->Data_model->db->where(array('wid'=>$wid))->delete('work_watch');

			//删除图片
			$images=$this->Data_model->getData(array('wid'=>$wid),'','','','work_image');
			foreach ($images as $key => $image) {
				@unlink(FCPATH.$image['image']);
			}
			$this->Data_model->db->where(array('wid'=>$wid))->delete('work_image');
			$this->Data_model->db->where(array('id'=>$wid))->delete('works');
			echo json_encode(array('errorcode'=>0,'message'=>'删除成功！'));
		}
	}

	function upload(){
		$return=array();
		$attrconfig = $this->Cache_model->loadConfig('attr');
		$basepath='/data/attachment/'.$attrconfig['userfolder'].'/'.$this->member->mname.date('/Y/m/');

		$ext_arr = array(
				'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
				'flash' => array('swf', 'flv'),
				'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'rm', 'rmvb'),
				'file' => array('gif', 'jpg', 'jpeg', 'png', 'bmp','doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
		);
		$return['baseurl']=$basepath;
		$save_path=FCPATH.$basepath;
		if (!file_exists($save_path)) {
			mkdir($save_path,0777,TRUE);
		}

		$filename=base_convert(microtime(), 10, 32);

		$uploadconfig['allowed_types'] = implode('|',$ext_arr['image']);
		$uploadconfig['upload_path'] = $save_path;
		$uploadconfig['max_size'] = $attrconfig['attr_maxsize']?$attrconfig['attr_maxsize']:0;
		$uploadconfig['encrypt_name']  = TRUE;
		$uploadconfig['remove_spaces']  = TRUE;
		$uploadconfig['overwrite']=FALSE;
		$uploadconfig['file_name']=$filename;
		$this->load->library('upload', $uploadconfig);
		if($this->upload->do_multi_upload('files') ){
			
			$return['errorcode']=0;
			$return['message']='上传成功！';
			$return['files']=$this->upload->get_multi_upload_data();
			foreach ($return['files'] as $key => $file) {
				$this->Data_model->addData(array(
					'mid'=>$this->member->mid,
					'wid'=>0,
					'image'=>$basepath.$file['file_name']
					),'work_image');
			}
		}else{
			$return['errorcode']=1;
			$return['error']=$this->upload->display_errors('','');
		}

		echo json_encode($return);
	}

	function upload_delete(){
		$file=$this->input->post('file',TRUE);
		$attrconfig = $this->Cache_model->loadConfig('attr');
		$basepath='/data/attachment/'.$attrconfig['userfolder'].'/'.$this->member->mname.'/';
		if(substr($file, 0, strlen($basepath))==$basepath){
			@unlink(FCPATH.$file);
			$this->Data_model->db->where(array(
				'mid'=>$this->member->mid,
				'image'=>$file
				))->delete('work_image');
			echo 'Deleted:';
		}else{
			echo 'Denied:';
		}
		
		echo $file;
	}
	
	//会员简历
	function member_info(){
		$where=array('mid'=>$this->member->mid);
		$info = $this->Data_model->getSingle($where,'member');
		return $info;
	}
	
	//会员简历修改
	function intro(){

		$post=$this->input->post(NULL,TRUE);
		if(!empty($post)){
			$result=array();
			$data = array_intersect_key($post,array('city'=>'','age'=>'','profession'=>'','honor'=>'','story'=>'','sex'=>'','email'=>'','mnick'=>'','isdetail'=>''));
			$this->Data_model->db->where(array('mid'=>$this->member->mid));
			$flag=$this->Data_model->db->update('member',$post);
			if($flag){
				$result['errorcode']=0;
				$result['error']='简历保存成功';
				$result['url']='member/index';
			}else{
				$result['errorcode']=1;
				$result['error']='简历保存失败';
			}
			echo json_encode($result);
		}
		else{
			$where=array('mid'=>$this->member->mid);
			$info=array();
			$info = $this->Data_model->getSingle($where,'member');
			$this->mview('intro',array(
				'memberinfo'=>$info,
			));
		}
	}
	function updateinfo(){
	
	}
	
	//会员页面子模板调用
	function mview($tpl='main',$data=array()){
		$data['subtpl']=$tpl;
		$this->view('member',$data);
		
	}

	
}